package com.parktech.sun.web.controller.management.unionnews;

import com.parktech.sun.domain.model.Constants;
import com.parktech.sun.domain.model.ContentEntity;
import com.parktech.sun.domain.model.unionnews.UnionNews;
import com.parktech.sun.domain.model.unionnews.UnionNewsGroup;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.service.unionnews.UnionNewsService;
import com.parktech.sun.utils.FileHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: Think
 * Date: 11-1-19
 * Time: 上午2:08
 */
@Controller
@RequestMapping("/management/unionnews")
public class UnionNewsController {

    private int pageSize = Constants.PAGINATION_PAGE_SIZE;

    private UnionNewsService unionNewsService;

    @Autowired
    public UnionNewsController(UnionNewsService unionNewsService) {
        this.unionNewsService = unionNewsService;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    @RequestMapping(value = "/search", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView search(@ModelAttribute UnionNewsSearchForm unionNewsSearchForm) {

        Page page = new Page(pageSize, unionNewsSearchForm.getPageNo());

        ModelAndView modelAndView = new ModelAndView("management/unionnews/unionNewsSearch");

        return modelAndView.addObject(
                unionNewsService.search(
                        unionNewsSearchForm.getTitle(), unionNewsSearchForm.getPublishStatus(), page));
    }

    @RequestMapping(value = "/search", method = RequestMethod.DELETE)
    public String delete(@RequestParam("unionNewsIds") Long[] unionNewsIds) {
        unionNewsService.deleteAll(unionNewsIds);
        return "redirect:search";
    }

    @ModelAttribute("unionNews")
    public UnionNews populateModel(HttpServletRequest request) {
        String strId = request.getParameter("id");

        if (strId == null || strId.equals("-1")) {
            return new UnionNews();
        }
        return unionNewsService.getById(new Long(strId));
    }

    @ModelAttribute("unionNewsGroup")
    public UnionNewsGroup populateGroup(HttpServletRequest request) {
        String strId = request.getParameter("id");

        if (strId == null || strId.equals("-1")) {
            return new UnionNewsGroup();
        }
        return unionNewsService.getGroupById(new Long(strId));
    }

    @ModelAttribute("allPublishStatus")
    public Map<Integer, String> populateAllPublishStatus() {
        Map<Integer, String> allPublishStatus = new HashMap<Integer, String>();
//        allPublishStatus.put(-1, "所有");
        allPublishStatus.put(0, "未发布");
        allPublishStatus.put(1, "已发布");
        return allPublishStatus;
    }

    @RequestMapping(value = "/{unionNewsId}", method = RequestMethod.GET)
    public String edit(@PathVariable Long unionNewsId, Model model) {
        UnionNews unionNews = unionNewsService.getById(unionNewsId);
        model.addAttribute(unionNews);
        return "management/unionnews/unionNewsForm";
    }

    @RequestMapping(value = "/{unionNewsId}/groups/list")
    public String listGroup(@PathVariable Long unionNewsId, Model model) {
        model.addAttribute(unionNewsService.getById(unionNewsId));
        return "management/unionnews/unionNewsGroupList";
    }

    @RequestMapping(value = "/{unionNewsId}/groups/list", method = RequestMethod.DELETE)
    public String deleteGroup(@RequestParam("unionNewsGroupIds") Long[] unionNewsGroupIds) {
        unionNewsService.deleteAll(UnionNewsGroup.class, unionNewsGroupIds);
        return "redirect:list";
    }

    @RequestMapping(value = "/{unionNewsId}/groups", method = RequestMethod.GET)
    public String addGroup(@PathVariable Long unionNewsId, Model model) {
        UnionNewsGroup unionNewsGroup = new UnionNewsGroup();
        unionNewsGroup.setUnionNews(new UnionNews(unionNewsId));
        model.addAttribute(unionNewsGroup);
        return "management/unionnews/unionNewsGroupForm";
    }

    @RequestMapping(value = "/{unionNewsId}/groups/{groupId}", method = RequestMethod.GET)
    public String editGroup(@PathVariable("unionNewsId") Long unionNewsId,
                           @PathVariable("groupId") Long groupId, Model model) {
        UnionNewsGroup unionNewsGroup = unionNewsService.getGroupById(groupId);
        model.addAttribute(unionNewsGroup);
        return "management/unionnews/unionNewsGroupForm";
    }

    @RequestMapping(value = "/{unionNewsId}/groups", method = {RequestMethod.POST, RequestMethod.PUT})
    public String saveGroup(@PathVariable("unionNewsId") Long unionNewsId, @ModelAttribute UnionNewsGroup unionNewsGroup) {
        unionNewsGroup.setUnionNews(unionNewsService.getById(unionNewsId));
        unionNewsService.saveOrUpdateGroup(unionNewsGroup);
        return "redirect:/management/unionnews/"+unionNewsId+"/groups/list";
    }

    @RequestMapping(value = "/{unionNewsId}/{unionNewsGroupId}/contents/{pageNo}/search")
    public String searchContent(@ModelAttribute UnionNewsSearchForm unionNewsSearchForm,
                                @PathVariable("unionNewsGroupId") Long unionNewsGroupId,
                                @PathVariable("unionNewsId") Long unionNewsId,
                                @PathVariable("pageNo")int pageNo, Model model) {
        model.addAttribute("grantedContents", unionNewsService.getGroupById(unionNewsGroupId).getContentEntityList());
        Page page = new Page(pageSize, unionNewsSearchForm.getPageNo());
        model.addAttribute(unionNewsService.searchContentEntity(unionNewsSearchForm.getTitle(), page));
        return "management/unionnews/unionNewsContentManagement";
    }

    @RequestMapping(value = "/{unionNewsId}/{unionNewsGroupId}/contents/{pageNo}/add")
    public String addContent(@ModelAttribute UnionNewsSearchForm unionNewsSearchForm,
                             @RequestParam("addContentEntityIds") Long[] addContentEntityIds,
                             @PathVariable("unionNewsId") Long unionNewsId,
                             @PathVariable("unionNewsGroupId") Long unionNewsGroupId) {

        UnionNewsGroup unionNewsGroup = unionNewsService.getGroupById(unionNewsGroupId);
        List<ContentEntity> contentEntityList = unionNewsGroup.getContentEntityList();
        for (Long addContentEntityId : addContentEntityIds) {
            ContentEntity contentEntity = new ContentEntity(addContentEntityId);
            if (!contentEntityList.contains(contentEntity)) {
                contentEntityList.add(new ContentEntity(addContentEntityId));
            }
        }
        unionNewsService.saveOrUpdateGroup(unionNewsGroup);
        return "redirect:search";
    }

    @RequestMapping(value = "/{unionNewsId}/{unionNewsGroupId}/contents/{pageNo}/delete")
    public String deleteContent(@ModelAttribute UnionNewsSearchForm unionNewsSearchForm,
                                @RequestParam("delContentEntityIds") Long[] delContentEntityIds,
                                @PathVariable("unionNewsId") Long unionNewsId,
                                @PathVariable("unionNewsGroupId") Long unionNewsGroupId) {

        UnionNewsGroup unionNewsGroup = unionNewsService.getGroupById(unionNewsGroupId);
        List<ContentEntity> contentEntityList = unionNewsGroup.getContentEntityList();
        for (Long delContentEntityId : delContentEntityIds) {
            ContentEntity contentEntity = new ContentEntity(delContentEntityId);
            if (contentEntityList.contains(contentEntity)) {
                contentEntityList.remove(contentEntity);
            }
        }
        unionNewsService.saveOrUpdateGroup(unionNewsGroup);
        return "redirect:search";
    }

    @RequestMapping(method = RequestMethod.GET)
    public String create(Model model) {
        model.addAttribute(new UnionNews());
        return "management/unionnews/unionNewsForm";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String save(@ModelAttribute @Valid UnionNews unionNews, BindingResult result,
                       @RequestParam("image") MultipartFile image,
                       HttpServletRequest request)
            throws IOException {

        if (result.hasErrors()) {
            return "management/unionnews/unionNewsForm";
        }
        unionNewsService.clearThenSaveOrUpdateBean(unionNews);

        if (image != null && !image.isEmpty()) {
            processImage(unionNews, image, request.getSession().getServletContext());
        }

        unionNewsService.saveOrUpdateBean(unionNews);

        return "redirect:/management/unionnews/search";
    }

    private void processImage(UnionNews unionNews, MultipartFile image, ServletContext servletContext) throws IOException {

        String unionNewsPath = servletContext.getRealPath("/upload/unionNews/" + unionNews.getId());
        File unionNewsDir = new File(unionNewsPath);
        if (!unionNewsDir.exists()) unionNewsDir.mkdirs();

        File imageFile = new File(unionNewsDir, image.getOriginalFilename());
        if (imageFile.exists()) {
            imageFile.delete();
        }
        FileHelper.saveFile(image.getInputStream(), imageFile);
        unionNews.setImageName(image.getOriginalFilename());
    }
}


